package com.dddframework.security.infras.config;

import com.dddframework.security.domain.phone.component.PhoneLoginSuccessHandler;
import com.dddframework.security.domain.thirdparty.component.ThirdPartyLoginSuccessHandler;
import com.dddframework.security.domain.auth.service.IUserDetailService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationEventPublisher;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

/**
 * 认证相关配置
 *
 * @author zhouzx
 */
@Primary
@Order(90)
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private ClientDetailsService clientDetailsService;
    @Autowired(required = false)
    private IUserDetailService userService;
    @Autowired
    private ThirdPartyProperties thirdPartyProperties;
    @Lazy
    @Autowired
    private AuthorizationServerTokenServices defaultAuthorizationServerTokenServices;
    @Autowired
    private AuthenticationEventPublisher authenticationEventPublisher;

    @Override
    @SneakyThrows
    protected void configure(HttpSecurity http) {
        http
                .formLogin()
                .loginPage("/token/login")
                .loginProcessingUrl("/token/form")
                .and()
                .authorizeRequests()
                .antMatchers(
                        "/token/**",
                        "/actuator/**",
                        "/phone/**",
                        "/thirdparty/**").permitAll()
                .anyRequest().authenticated()
                .and().csrf().disable()
                .apply(phoneSecurityConfigurer())
                .and().csrf().disable()
                .apply(thirdPartySecurityConfigurer());
    }

    /**
     * 不拦截静态资源
     */
    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/css/**");
    }

    @Bean
    @Override
    @SneakyThrows
    public AuthenticationManager authenticationManagerBean() {
        return super.authenticationManagerBean();
    }

    @Bean
    public AuthenticationSuccessHandler phoneLoginSuccessHandler() {
        return PhoneLoginSuccessHandler.builder()
                .clientDetailsService(clientDetailsService)
                .passwordEncoder(passwordEncoder())
                .defaultAuthorizationServerTokenServices(defaultAuthorizationServerTokenServices).build();
    }

    @Bean
    public PhoneSecurityConfig phoneSecurityConfigurer() {
        PhoneSecurityConfig phoneSecurityConfig = new PhoneSecurityConfig();
        phoneSecurityConfig.setLoginSuccessHandler(phoneLoginSuccessHandler());
        phoneSecurityConfig.setEventPublisher(authenticationEventPublisher);
        phoneSecurityConfig.setUserService(userService);
        return phoneSecurityConfig;
    }

    @Bean
    public AuthenticationSuccessHandler thirdPartyLoginSuccessHandler() {
        return ThirdPartyLoginSuccessHandler.builder()
                .clientDetailsService(clientDetailsService)
                .passwordEncoder(passwordEncoder())
                .defaultAuthorizationServerTokenServices(defaultAuthorizationServerTokenServices).build();
    }

    @Bean
    public ThirdPartySecurityConfig thirdPartySecurityConfigurer() {
        ThirdPartySecurityConfig thirdPartySecurityConfig = new ThirdPartySecurityConfig();
        thirdPartySecurityConfig.setLoginSuccessHandler(thirdPartyLoginSuccessHandler());
        thirdPartySecurityConfig.setEventPublisher(authenticationEventPublisher);
        thirdPartySecurityConfig.setUserService(userService);
        thirdPartySecurityConfig.setThirdPartyProperties(thirdPartyProperties);
        return thirdPartySecurityConfig;
    }

    /**
     * https://spring.io/blog/2017/11/01/spring-security-5-0-0-rc1-released#password-storage-updated
     * Encoded password does not look like BCrypt
     *
     * @return PasswordEncoder
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

}